/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.st.processor;

import java.io.FileReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.bambamboo.st.IProcessor;
import com.bambamboo.st.util.StringUtil;

public class ScriptProcessor extends AbstractProcessor implements IProcessor {

	/**
	 * the script file location
	 */
	private String script;
	/**
	 * not required if the engine can be specified by the script file extension
	 */
	private String engine;

	public byte[] getResponse(byte[] requestBuf) throws Exception {
		if (StringUtil.isEmpty(script))
			throw new Exception("script not specified yet!");

		ScriptEngineManager factory = new ScriptEngineManager();
		String ext = StringUtil.getFileExtension(script);
		ScriptEngine engine = factory.getEngineByExtension(ext);
		if (engine == null) {
			engine = factory.getEngineByName(getEngine());
		}
		engine.put("request", requestBuf);
		engine.put("charsetName", getCharset());

		Object response = engine.eval(new FileReader(script));
		if (response == null) {
			response = engine.get("response");
		}
		if (response != null) {
			if (response instanceof byte[])
				return (byte[]) response;
			else {
				String resp = response.toString();
				return resp.getBytes(getCharset());
			}
		}

		return null;
	}

	public String getScript() {
		return script;
	}

	public void setScript(String script) {
		this.script = script;
	}

	public String getEngine() {
		return engine;
	}

	public void setEngine(String engine) {
		this.engine = engine;
	}

	@Override
	public String toString() {
		String e = getEngine();
		if (StringUtil.isEmpty(e)) {
			e = StringUtil.getFileExtension(getScript());
		}

		return String.format("%s Script Handler with script: %s", e, getScript());
	}
}
